$(function() {
    updateDepList();
    $('.dep-id-input').val("2");
    $('.content-title-p').on('click', function() {
        $(this).children('i').toggleClass('icon-xiala icon-shangla');
        $(this).parent().next().slideToggle();
    })

    // 全选
    $(document).on('click', '.add-staff-head .checked', function() {
            if (checkStatus == 0) {
                checkStatus = 1;
                $(this).addClass('on_check');
                $(this).parents('table').first().find('.add-staff-body .checked').addClass("on_check");
            } else if (checkStatus == 1) {
                checkStatus = 0;
                $(this).removeClass('on_check');
                $(this).parents('table').first().find('.add-staff-body .checked').removeClass("on_check");
            }
        })
    // 单选
    $(document).on('click', '.add-staff-body .checked', function() {
        $(this).toggleClass("on_check");
        if (checkStatus == 1 && $('.add-staff-head .checked').hasClass('on_check')) { //如果全选
            //全选复选框取消
            $('.add-staff-head .checked').removeClass('on_check');
        }
    })

    //上一页
    $('.staff-prev').on('click', function() {
        if ($('.page-num')[0].value > 1) {
            $('.page-num')[0].value--;
            viewStaff($('.page-num')[0].value);
        } else {
            setAlert('已至第1页');
        }
    })

    // 下一页
    $('.staff-next').on('click', function() {
        $('.page-num')[0].value++;
        viewStaff($('.page-num')[0].value);

    })

    // 跳转页
    $('.go-btn').click(function() {
        var pgNum = parseInt($('.goPage').val());
        if (isNaN(pgNum)) {
            setAlert('请正确输入页码');
        } else if (pgNum > totalNum || pgNum < 1) {
            setAlert('无此页');
        } else {
            viewStaff(pgNum);
        }

    })

    // 添加员工
    $('.btn-add').click(function() {
        // alert(111)
            loading();
            var staffArr = [];
            var $onCheck = $('.add-staff-body .on_check');
            for (var i = 0; i < $onCheck.length; i++) {
                staffArr.push($onCheck.eq(i).children('.check-input').data('id'));
            }
            var content = JSON.stringify(staffArr);
            var depId = $('.dep-id-input').val();
            $.ajax({
                url: "/epi/department/staff/" + depId,
                data: content,
                type: "POST",
                contentType : "application/json",
                dataType : "json",
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('添加失败！');
                    } else if (status == 401) {
                        setAlert('添加失败，员工已在该部门！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        setAlert('添加成功！');
                        $('.add-modal,.mask').fadeOut();
                        // fillDep('修改成功',
                        // validateDep().depName,
                        // validateDep().depType,
                        // validateDep().depNum,
                        // validateDep().depFax,
                        // validateDep().depPhone,
                        // validateDep().areaName,
                        // validateDep().areaSite);
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }

            })
        })
        // 查看指定员工信息
    $(document).on('click', '.icon-gengduo', function() {
        loading();
        var thisId = $(this).children('input').val();
        $.ajax({
            url: path + "json/staff.json", //'/epi/staff/staffs/'+thisId,//path+"json/staff.json",
            // data: {
            //     id:thisId
            // },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                loadingHide();
                var myTemplate = Handlebars.compile($("#staff-info-template").html());
                // console.log(myTemplate(data))
                $('.staff-info-div').html(myTemplate(data));
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
        fadeModal('.information-modal');
    })

    // 删除员工
    $(document).on('click', '.icon-lajitong', function() {
        var thisId = $(this).children('input').val();
        var departmentId = $('.dep-id-input').val();
        //console.log(thisId);
        setConfirm('是否确定删除此员工', function() {
            loading();
            $.ajax({
                url: "/epi/department/staff/" + departmentId + "/" + thisId,
                type: "DELETE",
                dataType: 'json',
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除员工失败！');
                    } else if (status == 200) {
                        $('tr').removeClass('selected');
                        $(this).parents('tr').first().addClass('selected');
                        $('.selected').remove();
                        setAlert('删除员工成功');
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });

        })
    })

    // 修改部门信息模态框（内容页）
    $('.edit-btn').on('click', function(e) {
        // 填充表单
        $('.form-control .dep-name').val($('.dep-info-name').html()), //部门名称
            $('.dep-type').val($('.dep-info-type').html()), //部门类别
            $('.dep-num').val($('.dep-info-num').html()), //部门编号
            $('.dep-date').val($('.dep-info-date').html()), //创建日期
            $('.dep-fax').val($('.dep-info-fax').html()), //传真
            $('.dep-phone').val($('.dep-info-phone').html()), //电话
            $('.area-name').val($('.area-info-name').html()), //区域名称
            $('.area-site').val($('.dep-info-site').html()); //区域地址
        $('.dep-btn').attr('class', 'btn dep-btn edit-dep-btn');
        fadeModal('.edit-modal');
    })

    //部门人员信息
    $('.add-btn').on('click', function() {
        // alert('222')
        viewStaff(1);
        fadeModal('.add-modal');
    })

    // 修改部门
    $(document).on('click', '.edit-dep-btn', function() {
        loading();
        // console.log(validateDep());
        if (validateDep() != undefined) {
            $.ajax({
                url: "/epi/department/",
                data: JSON.stringify({
                    //                     _method: "PUT",
                    departmentName: validateDep().depName,
                    departmentId: validateDep().depNum,
                    departmentType: validateDep().depType,
                    departmentAddress: validateDep().areaSite,
                    departmentPhone: validateDep().depPhone,
                    departmentFax: validateDep().depFax,
                    departmentAreaName: validateDep().areaName
                }),
                type: "PUT",
                dataType: 'json',
                contentType: "application/json",
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('修改失败！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        $('.edit-modal,.mask').fadeOut();
                        // fillDep('修改成功',
                        // validateDep().depName,
                        // validateDep().depType,
                        // validateDep().depNum,
                        // validateDep().depFax,
                        // validateDep().depPhone,
                        // validateDep().areaName,
                        // validateDep().areaSite);
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });

        }
    });

    $('.dep-cancel-btn').on('click', function() {
        $('.edit-modal,.mask').fadeOut();
    });

    $('.dep-date').fdatepicker();

    $(document).on('click', '.btn-info', function() {
        $('.information-modal,.mask').fadeOut();
    });

    $(document).on('mousedown', '.dep-li', function(e) {
        var depId = $(this).children('.dep-li-id').val();
        var depPreId = $(this).children('.dep-li-pre-id').val();
        $('.dep-id-input').val(depId);
        $('.dep-pre-id-input').val(depPreId);
        // alert(depPreId)
        //屏蔽右键菜单
        document.oncontextmenu = function() {
            return false;
        }

        if (e.which == 3) {

            $('.dep-li').removeClass('selected');
            $(this).addClass('selected');
            $('.right-menu').css({
                'left': mousePos(e).x,
                'top': mousePos(e).y
            })
            $('.right-menu').fadeIn();
        }

        return false;
    })
    $(document).click(function() {
        $('.right-menu').hide()
    })

    // 创建部门模态框
    $('.creat-dep,.creat-child-dep').on('click', function(e) {
        // 清空表单
        $('.form-control .dep-name').val(''), //部门名称
            $('.dep-type').val(''), //部门类别
            $('.dep-num').val(''), //部门编号
            // depDate = $('.dep-date').val(),//创建日期
            $('.dep-fax').val(''), //传真
            $('.dep-phone').val(''), //电话
            $('.area-name').val(''), //区域名称
            $('.area-site').val(''); //区域地址
        // 改变按钮class
        $('.dep-btn').attr('class', 'btn dep-btn creat-dep-btn')
        fadeModal('.edit-modal');
    })

    // 创建子部门模态框
    $('.creat-dep,.creat-child-dep').on('click', function(e) {
        // 清空表单
        $('.form-control .dep-name').val(''), //部门名称
            $('.dep-type').val(''), //部门类别
            $('.dep-num').val(''), //部门编号
            // depDate = $('.dep-date').val(),//创建日期
            $('.dep-fax').val(''), //传真
            $('.dep-phone').val(''), //电话
            $('.area-name').val(''), //区域名称
            $('.area-site').val(''); //区域地址
        // 改变按钮class
        $('.dep-btn').attr('class', 'btn dep-btn creat-child-dep-btn')
        fadeModal('.edit-modal');
    })

    // 创建部门
    $(document).on('click', '.creat-dep-btn', function() {
        loading();
        //console.log(validateDep());
        if (validateDep() != undefined) {
            $.ajax({
                url: "/epi/department/",
                data: JSON.stringify({
                    departmentName: validateDep().depName,
                    departmentId: validateDep().depNum,
                    departmentParentId: $('.dep-pre-id-input').val(),
                    //departmentParentId:1,
                    departmentType: validateDep().depType,
                    departmentAddress: validateDep().areaSite,
                    departmentPhone: validateDep().depPhone,
                    departmentFax: validateDep().depFax,
                    departmentAreaName: validateDep().areaName
                }),
                type: "POST",
                dataType: 'json',
                contentType: "application/json",
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('部门创建失败失败！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        setAlert('部门创建成功');
                        $('.edit-modal,.mask').fadeOut();
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });

        }
    });

    // 创建子部门
    $(document).on('click', '.creat-child-dep-btn', function() {
        loading();
        //console.log(validateDep());
        if (validateDep() != undefined) {
            $.ajax({
                url: "/epi/department/",
                data: JSON.stringify({
                    departmentName: validateDep().depName,
                    departmentId: validateDep().depNum,
                    departmentParentId: $('.dep-id-input').val(),
                    //departmentParentId:1,
                    departmentType: validateDep().depType,
                    departmentAddress: validateDep().areaSite,
                    departmentPhone: validateDep().depPhone,
                    departmentFax: validateDep().depFax,
                    departmentAreaName: validateDep().areaName
                }),
                type: "POST",
                dataType: 'json',
                contentType: "application/json",
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('部门创建失败失败！');
                    } else if (status == 200) {
                        var thisId = $('.dep-id-input').val();
                        updateDepList(thisId);
                        setAlert('部门创建成功');
                        $('.edit-modal,.mask').fadeOut();
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });

        }
    });

    // 修改右键菜单模态框（右键菜单）
    $('.edit-dep').click(function() {
        loading();
        var depId = $('.dep-id-input').val();
        //alert(depId);
        $.ajax({
            url: '/epi/department/departments/' + $('.dep-id-input').val(),
            //url: '/epi/department/departments/1',
            type: "GET",
            dataType: 'json',
            success: function(data) {
                loadingHide();
                //console.log(JSON.stringify(data));
                $('.form-control .dep-name').val(data.departmentName), //部门名称
                    $('.dep-type').val(data.departmentType), //部门类别
                    $('.dep-num').val(data.departmentId), //部门编号
                    // $('.dep-date').val(data.departmentCreateTime),//创建日期
                    $('.dep-fax').val(data.departmentFax), //传真
                    $('.dep-phone').val(data.departmentPhone), //电话
                    $('.area-name').val(data.departmentAreaName), //区域名称
                    $('.area-site').val(data.departmentAddress); //区域地址
                $('.dep-btn').attr('class', 'btn dep-btn edit-dep-btn');
                fadeModal('.edit-modal');
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });

    })

    // 删除部门
    $('.delete-dep,.delete-dep-btn').click(function() {
        setConfirm('确认删除此部门？', function() {
            loading();
            $.ajax({
                url: "/epi/department/" + $('.dep-id-input').val(),
                type: "DELETE",
                dataType: 'json',
                success: function(data) {
                    loadingHide();
                    var status = data.STATUS;
                    if (status == 500) {
                        setAlert('非法操作！');
                    } else if (status == 400) {
                        setAlert('删除部门失败！');
                    } else if (status == 200) {
                        setAlert('部门删除成功');
                        updateDepList();
                    } else {
                        setAlert('系统繁忙，请刷新重试');
                    }
                },
                error: function() {
                    setAlert('系统繁忙，请刷新重试');
                }
            });

        })
    })

    //部门搜索
    $('.dep-search-btn').click(function() {
        var searchContent = $('.dep-search-input').val();
        for (var i = 0; i < $('.dep-li').length; i++) {
            //console.log($('.dep-li').eq(i).text())
            if ($('.dep-li').eq(i).text() == searchContent) {
                $('.dep-li').eq(i).dblclick();
            }
        }
    })

    //双击部门列表-选择部门
    $('.dep-list-div').on('dblclick', '.dep-li', function() {
        content = "";
        depObj = [];
        var id = $(this).children('.dep-li-id').val();
        // alert(id);
        updateDepList(id);
        $('.dep-id-input').val(id);
    })

    //单击部门列表－展开收起
    $('.dep-list-div').on('click', '.dep-li', function() {
        if ($(this).children('i').length > 0) {
            $(this).children('i').toggleClass('icon-xiala icon-shangla')
            $(this).next('ul').slideToggle();
        }
    })

    //点击面包屑
    $('#content').on('click', '#breadcrumb .tip-bottom', function() {
        content = "";
        depObj = [];
        var id = $(this).children('input').val();
        updateDepList(id);

    })

    //搜索员工
    $('.search-btn').click(function(){
        viewStaff(1);
    })


})

var content = "";
/**
 * [creatDeplist 创建部门列表]
 * @param  {[Object]} data [部门数据]
 * @return {[String]} content [DOM结构]
 */
function creatDeplist(data) {
    // console.log(data.length)
    content += "<ul>";
    for (var i = 0; i < data.length; i++) {
        if (!data[i].hasOwnProperty("children")) {
            content += '<li class="dep-li">' +
                '<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>' +
                '<span class="dep-name">' + data[i].departmentName + '</span>' +
                '<input type="hidden" value="' + data[i].departmentId + '" class="dep-li-id">' +
                '<input type="hidden" value="' + data[i].departmentParentid + '" class="dep-li-pre-id">' +
                '</li>';
        } else {
            content += '<li class="dep-li">' +
                '<i class="iconfont icon-xiala"></i>' +
                '<span class="dep-name">' + data[i].departmentName + '</span>' +
                '<input type="hidden" value="' + data[i].departmentId + '" class="dep-li-id">' +
                '<input type="hidden" value="' + data[i].departmentParentid + '" class="dep-li-pre-id">' +
                '</li>';
            // var treeData = transData(data[i].chindren,"departmentId","departmentParentid","children");
            creatDeplist(data[i].children);
        }
    }
    content += "</ul>";
    return content;
}

/**
 * [updateDepList 更新部门列表]
 * @param  {[type]} id [所显示的部门id]
 */
function updateDepList(id) {
    loading();
    $.ajax({
        url: "/epi/department/departments",
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            var treeData = transData(data, "departmentId", "departmentParentid", "children");
            $('.dep-list').html(creatDeplist(treeData));
            // // 面包屑导航,默认显示第一个部门
            // console.log(id);
            if (id == undefined) {
                var thisData = treeData[0];
                while (thisData.hasOwnProperty("children")) {
                    thisData = thisData.children[0];
                }
                setBread(thisData.departmentId);
                viewDepInfor(thisData.departmentId);
                viewStaffInfor(thisData.departmentId);
            } else {
                setBread(id);
                viewDepInfor(id);
                viewStaffInfor(id);
            }
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试1');
        }
    });
}

/**
 * [validateDep 部门操作验证]
 * @return {[Object]} [部门信息]
 */
function validateDep() {
    var depName = $('.form-control .dep-name').val(), //部门名称
        depType = $('.dep-type').val(), //部门类别
        depNum = $('.dep-num').val(), //部门编号
        // depDate = $('.dep-date').val(),//创建日期
        depFax = $('.dep-fax').val(), //传真
        depPhone = $('.dep-phone').val(), //电话
        areaName = $('.area-name').val(), //区域名称
        areaSite = $('.area-site').val(); //区域地址
    if (depName == '') {
        setAlert('请填写部门名称');
    } else if (depType == '') {
        setAlert('请输入部门类别');
    } else if (depPhone == '') {
        setAlert('请输入电话号码');
    } else if (areaSite == '') {
        setAlert('请输入区域所在地');
    } else {
        return {
            depName: depName,
            depType: depType,
            depNum: depNum,
            depFax: depFax,
            depPhone: depPhone,
            areaName: areaName,
            areaSite: areaSite
        }
    }
}

/**
 * [fillDep 填充信息面板]
 * @param  {[String]} string   [提示文字]
 * @param  {[String]} depName  [部门名称]
 * @param  {[String]} depType  [部门类别]
 * @param  {[String]} depNum   [部门编号]
 * @param  {[String]} depFax   [部门传真]
 * @param  {[String]} depPhone [部门电话]
 * @param  {[String]} areaName [区域名称]
 * @param  {[String]} areaSite [区域地址]
 */
function fillDep(string, depName, depType, depNum, depFax, depPhone, areaName, areaSite) {
    setAlert(string);
    $('.dep-info-name').html(depName);
    $('.dep-info-type').html(depType);
    $('.dep-info-num').html(depNum);
    // $('.dep-info-date').html(depDate);
    $('.dep-info-fax').html(depFax);
    $('.dep-info-phone').html(depPhone);
    $('.area-info-name').html(areaName);
    $('.dep-info-site').html(areaSite);
    $('.edit-modal').fadeOut();
}

/**
 * [mousePos 获取浏览器坐标]
 * @param  {[type]} e [description]
 * @return {[type]}   [x,y坐标]
 */
function mousePos(e) {
    var x, y;
    var e = e || window.event;
    return {
        x: e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
        y: e.clientY + document.body.scrollTop + document.documentElement.scrollTop
    };
};

/**
 * [setBread 面包屑导航]
 * @param {[Object]} tipBottom [指定部门id]
 */
var depObj = [];

function setBread(id) {
    // console.log(id)
    var idList = $('.dep-li-id');
    var breadcrumb = '';
    // console.log(idList.length)
    for (var i = 0; i < idList.length; i++) {
        // console.log(id);

        var idListVal = parseInt(idList.eq(i).val());
        // console.log(idListVal)
        if (id == idListVal) {
            // console.log('-------------------------------')
            var depName = $('.dep-name').eq(i).text();
            //console.log(depName)
            var preId = $('.dep-li-pre-id').eq(i).val();
            // console.log(depName)
            depObj.push({
                id: id,
                preId: preId,
                name: depName
            })
            if (preId != "") {
                setBread(preId);
                // console.log(preId)   
            } else {
                //console.log(depObj)
                return depObj;
            }
        }
    }
    if (depObj != '') {
        for (var j = depObj.length - 1; j >= 0; j--) {
            breadcrumb += '<a href="#" title="' + depObj[j].name + '" class="tip-bottom">' +
                '<i class="iconfont icon-home"></i>' +
                depObj[j].name +
                '<input type="hidden" value="' + depObj[j].id + '">' +
                '</a>';
        }
        //console.log(breadcrumb)
        $('#breadcrumb').html(breadcrumb);
    }
}

/**
 * [viewDepInfor 查询指定部门信息]
 * @param  {[type]} id [指定部门id]
 */
function viewDepInfor(id) {
    loading();
    $.ajax({
        url: '/epi/department/departments/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            var myTemplate = Handlebars.compile($("#dep-info-template").html());
            $('.dep-information').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}

/**
 * [viewStaffInfor 查询指定部门的员工信息]
 * @param  {[type]} id [指定部门id]
 */
function viewStaffInfor(id){
    loading();
    $.ajax({
        url: '/epi/department/staff/staffs/'+id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            loadingHide();
            var myTemplate = Handlebars.compile($("#staff-template").html());
            //console.log(data);
            //console.log(myTemplate(data))
            $('.staff-body').html(myTemplate(data));
        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}
// 员工总页数
var totalNum = 0;
//查询所有员工
function viewStaff(pageNum, records) {
    if (records == undefined) {
        records = 10;
    }
    var key = $('.search-input').val();
    if(key == "")
        key = "0";
    var depId = $('.dep-id-input').val();
    loading();
    $.ajax({
        url: "/epi/department/"+depId+"/staffs/" + key + "/" +pageNum+"/"+records,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            //console.log(data);
            //console.log(JSON.stringify(data));
            loadingHide();
            totalNum = parseInt(data.totalCount);
            $('.total-page-num').text(totalNum);
            $('.crt-page-num').text(pageNum);
            if (data.length != 0) {
                var myTemplate = Handlebars.compile($("#add-staff-template").html());
                console.log(JSON.stringify(data));
                //console.log(myTemplate(data));
                $('.add-staff-body').html(myTemplate(data.persons));
            } else {
                setAlert('无更多数据');
                $('.page-num')[0].value--;
            }

        },
        error: function() {
            setAlert('系统繁忙，请刷新重试');
        }
    });
}
